<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="(e) => {
        (searchlist = { ...e }), (currentPage = 1), getTableDataList();
      }
        ">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData :tableThead="tableThead" :dataList="dataList" :config="table_config"
        @selection-change="selectionChange">
        <template v-slot:completeStatus="{ row }">
          <span>{{ row.completeStatus ? "是" : "否" }}</span>
        </template>
        <template v-slot:viewList="{ row }">
          <el-button v-if="!row.index" class="text-btn-cursor" type="text" size="small"
            @click="lookInfo(row.arriveOrderNo)">
            <i class="el-icon-view"></i>查看到货明细
          </el-button>
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="changePageSize" :size="pageSize" @current-change="handleCurrentChange"
        :page="currentPage" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false" :title="titleText" :visible.sync="dialogFormVisible"
        @close="cancel('formData')">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <!-- 添加 -->
          <template v-for="(item, index) in formDatalists">
            <el-form-item v-if="item.edit !== 'edit' && nowChanceStau === 'add'" :key="index" :label="item.name + ':'"
              :prop="item.type === 'Select' ? item.selectValue : item.prop" class="w50p" :rules="item.isCheck
                ? rules[item.prop]
                : [
                  {
                    required: item.required,
                    message: item.name + '不能为空',
                    trigger: item.type === 'input' ? 'blur' : 'change',
                  },
                ]
                ">
              <el-input v-if="item.type === 'input'" v-model="formData[`${item.prop}`]" :placeholder="'请输入' + item.name"
                clearable class="w100p" :disabled="item.prop !== 'remarks'" />
              <el-select v-if="item.type === 'Select'" v-model="formData[`${item.selectValue}`]" filterable
                class="w100p" :placeholder="'请选择' + item.name" clearable @change="getSelectData($event, item.prop)">
                <el-option v-for="(items, indexs) in item.typeObj.list" :key="indexs" :label="items.name"
                  :value="items.value" />
              </el-select>
              <el-date-picker v-if="item.type === 'TimePicker'" v-model="formData[`${item.prop}`]" type="datetime"
                class="w100p" value-format="yyyy-MM-dd HH:mm" :placeholder="'选择' + item.name"
                @change="timeEvent($event, item.prop)" />
            </el-form-item>
          </template>
          <!-- 选择到货商品 -->
          <el-divider v-if="nowChanceStau === 'add'" content-position="left">到货明细</el-divider>
          <el-form-item v-if="nowChanceStau === 'add'" label="到货商品 :" class="w50p">
            <el-checkbox-group v-model="formData.arrivalGoodsList" @change="chooseGoods">
              <el-checkbox v-for="(items, indexs) in arrivalGoodsList" :key="indexs" :label="items">{{
                items.materialName
              }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <div v-for="(orderDetail, index) in formData.arriveOrderDetailList" :key="orderDetail.key"
            class="w100p xunhuan">
            <div class="w100p goods">到货商品{{ index + 1 }}</div>
            <el-form-item label="商品名称 :" :prop="'arriveOrderDetailList.' + index + '.materialNo'" class="w50p" :rules="[
              {
                required: true,
                message: '商品名称不能为空',
                trigger: 'change',
              },
            ]">
              <el-select v-model="orderDetail.materialNo" placeholder="请选择商品（物料）名称" clearable disabled
                @change="getGoods($event, index)">
                <el-option v-for="(items, indexs) in materialList" :key="indexs" :label="items.materialName"
                  :value="items.materialNo" />
              </el-select>
            </el-form-item>

            <el-form-item label="收货仓库 :" :prop="'arriveOrderDetailList.' + index + '.stordocNo'" class="w50p">
              <el-select v-model="orderDetail.stordocNo" placeholder="请选择收货仓库" clearable>
                <el-option v-for="(items, indexs) in stordocList" :key="indexs" :label="items.stordocName"
                  :value="items.stordocNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="批号 :" :prop="'arriveOrderDetailList.' + index + '.lotNumber'" class="w50p" :rules="[
              { required: true, message: '批号不能为空', trigger: 'change' },
            ]">
              <el-input v-model="orderDetail.lotNumber" clearable placeholder="输入批号(用于区分同一商品不同采购的批次)" />
            </el-form-item>
            <el-form-item label="单位 :" :prop="'arriveOrderDetailList.' + index + '.castUnitNo'" class="w50p" :rules="[
              { required: true, message: '单位不能为空', trigger: 'change' },
            ]">
              <el-select v-model="orderDetail.castUnitNo" placeholder="请选择单位" clearable>
                <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                  :value="items.unitNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="应到数量 :" :prop="'arriveOrderDetailList.' + index + '.shouldArriveNum'"
              class="w50p numberUnit" :rules="[
                { required: true, message: '数量不能为空', trigger: 'blur' },
                {
                  pattern: /^\d+$/,
                  message: '值该为正整数',
                  trigger: ['change', 'blur'],
                },
              ]">
              <el-input v-model="orderDetail.shouldArriveNum" clearable class="one" disabled placeholder="请输入数量" />
              <el-select v-model="orderDetail.castUnitNo" placeholder="单位" class="two" clearable>
                <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                  :value="items.unitNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="到货数量 :" :prop="'arriveOrderDetailList.' + index + '.arriveNum'" class="w50p numberUnit"
              :rules="[
                { required: true, message: '数量不能为空', trigger: 'blur' },
                {
                  pattern: /^\d+$/,
                  message: '值该为正整数',
                  trigger: ['change', 'blur'],
                },
              ]">
              <el-input v-model="orderDetail.arriveNum" clearable class="one" placeholder="请输入数量" />
              <el-select v-model="orderDetail.castUnitNo" placeholder="单位" class="two" clearable>
                <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                  :value="items.unitNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="换算率 :" :prop="'arriveOrderDetailList.' + index + '.exchangeRate'" class="w50p" :rules="[
              {
                pattern:
                  /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                message: '值为大于0的数',
                trigger: ['change', 'blur'],
              },
              {
                required: true,
                message: '换算率不能为空',
                trigger: 'change',
              },
            ]">
              <el-input v-model="orderDetail.exchangeRate" clearable placeholder="请输入换算率" />
            </el-form-item>
            <div class="zhu w50p">
              <el-form-item label="主数量&主单位 :" :prop="'arriveOrderDetailList.' + index + '.primaryQuantity'"
                style="width: 82%" :rules="[
                  {
                    pattern:
                      /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                    message: '值为大于0的数',
                    trigger: ['change', 'blur'],
                  },
                  { required: true, message: '数量不能为空', trigger: 'blur' },
                ]">
                <el-input v-model="orderDetail.primaryQuantity" clearable disabled placeholder="请输入主数量" />
              </el-form-item>
              <el-form-item :prop="'arriveOrderDetailList.' + index + '.unitNo'" style="width: 18%" :rules="[
                {
                  required: true,
                  message: '主单位不能为空',
                  trigger: 'change',
                },
              ]">
                <el-select v-model="orderDetail.unitNo" placeholder="请选择单位" disabled clearable>
                  <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                    :value="items.unitNo" />
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="到货日期 :" :prop="'arriveOrderDetailList.' + index + '.arriveTime'" class="w50p" :rules="[
              { required: true, message: '到货不能为空', trigger: 'change' },
            ]">
              <el-date-picker v-model="orderDetail.arriveTime" type="datetime" value-format="yyyy-MM-dd HH:mm" clearable
                placeholder="请选择时间" />
            </el-form-item>
            <el-form-item label="生产日期 :" :prop="'arriveOrderDetailList.' + index + '.produceDate'" class="w50p">
              <el-date-picker v-model="orderDetail.produceDate" type="date" value-format="yyyy-MM-dd" clearable
                placeholder="请选择时间" />
            </el-form-item>
            <el-form-item label="保质期/天 :" :prop="'arriveOrderDetailList.' + index + '.lifeDays'" class="w50p" :rules="[
              {
                pattern: /^\d+$/,
                message: '值该为正整数',
                trigger: ['change', 'blur'],
              },
              {
                required: true,
                message: '保质期不能为空',
                trigger: 'change',
              },
            ]">
              <el-input v-model="orderDetail.lifeDays" clearable placeholder="请输入数量"
                @change="getCount($event, index)" />
            </el-form-item>
            <el-form-item label="失效日期 :" :prop="'arriveOrderDetailList.' + index + '.expirationDate'" class="w50p">
              <el-date-picker v-model="orderDetail.expirationDate" type="date" value-format="yyyy-MM-dd" clearable
                placeholder="请选择时间" @change="getCount($event, index)" />
            </el-form-item>
          </div>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button v-if="nowChanceStau === 'add'" class="zh-button-two" type="primary" @click="save('formData')">保
            存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import TableData from "@/components/TableData";
import BtnSlot from "@/components/BtnSlot";

import { mymixin } from "@/utils/mixins";
import supplierApi from "@/api/livestock-manage/purchaseManage/supplier";
import unitApi from "@/api/basic-info-manage/unit-manage";
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage";
import orderApi from "@/api/livestock-manage/purchaseManage/purchaseOrder";
import orderDetailApi from "@/api/livestock-manage/purchaseManage/orderDetail";
import warehouseApi from "@/api/livestock-manage/storage-manage/warehouse-manage";
import personApi from "@/api/livestock-manage/personnel-cost-mansge/staff-manage";
import arrivalGoodsApi from "@/api/livestock-manage/purchaseManage/arrival-notice";
import arrivalDetailAoi from "@/api/livestock-manage/purchaseManage/arrival-detail";
import { mapGetters } from "vuex";
export default {
  name: "SheepInformation",
  components: { SearchForm, TableData, Pagination, MainSlot, BtnSlot },
  mixins: [mymixin],
  data() {
    return {
      formItemList: [
        {
          label: "采购订单编号",
          type: "input",
          param: "orderNo",
          isShow: true,
        },
        {
          selectOptions: [],
          label: "供应商名称",
          type: "select",
          param: "supplierNo",
          multiple: false,
          isShow: true,
        },
        {
          label: "采购员",
          param: "buyerName",
          isShow: true,
          type: "input",
        },
        {
          label: "收货人",
          param: "personNo",
          selectOptions: [],
          isShow: true,
          multiple: false,
          type: "select",
        },
        {
          label: "订单日期",
          param: "orderTime",
          isShow: true,
          type: "date",
        },
      ], //搜索
      selectionList: [],
      tableThead: [],
      btnList: ["add"],
      selectIndex: 0,
      total: 100,
      currentPage: 1,
      dataList: [],
      SupplierList: [],
      // 配置项
      table_config: {
        isCheckBox: false,
        isOperation: true,
        // 表格操作列
        operation: {
          label: "操作",
          width: "150",
          cols: [
            {
              label: "入库",
              type: "primary",
              flag: "inStorage",
              handleRow: this.handleRow,
            }
          ],
        },
      },
      // ===================================下面可能是用不上的，但是不敢删
      searchlist: {},
      tableColumn: [],
      formConfig: [
        {
          label: "采购订单编号",
          prop: "orderNo",
          type: "select",
          options: [],
          optionKey: { label: "name", value: "value" },
        },
        {
          label: "供应商",
          prop: "supplierNo",
          type: "select",
          options: [],
          optionKey: { label: "name", value: "value" },
        },
        {
          label: "采购员",
          prop: "buyerName",
          type: "input",
        },
        {
          label: "收货人",
          prop: "personNo",
          type: "select",
          options: [],
          optionKey: { label: "name", value: "value" },
        },
        {
          label: "到货日期",
          prop: "arriveTime",
          type: "date",
        },
      ],
      forderStatus: 0,
      arrivalGoodsList: [],
      selectedStaffList: [],
      stordocList: [],
      unitList: [],
      materialList: [],
      personList: [],
      formData: {
        arriveOrderDetailList: [],
      },
      // selectValue 用于传递select的编号
      formDatalists: [
        {
          type: "Select",
          prop: "orderNo",
          selectValue: "orderNo", // input Select Checkbox TimePicker
          typeObj: {},
          name: "采购订单编号",
          required: true,
        },
        {
          type: "Select",
          prop: "supplierName",
          selectValue: "supplierNo",
          typeObj: {},
          name: "供应商",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "buyerName",
          typeObj: {},
          name: "采购员",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalQuantity",
          typeObj: {},
          name: "总数量",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalPrice",
          typeObj: {},
          name: "价税合计/元",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "",
          typeObj: {},
          name: "到货明细",
          edit: "edit",
          required: true,
          notSearch: true,
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "receiverName",
          selectValue: "personNo",
          typeObj: {},
          name: "收货人",
          required: true,
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          prop: "arriveTime",
          typeObj: {},
          name: "到货日期",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "remarks",
          typeObj: {},
          name: "备注",
          notSearch: true,
        },
      ],
      rules: {},
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {
    formData: {
      deep: true,
      handler(val) {
        if (val.arriveOrderDetailList) {
          //
        }
        sum(1);
        function sum(arr) {
          let s = 0;
          for (let i = arr.length - 1; i >= 0; i--) {
            s += parseInt(arr[i]);
          }
          return s;
        }
      },
    },
  },
  created() {
    let list = [];
    this.formDatalists.forEach((el) => {
      let obj = {
        isShow: true,
        label: el.name,
      };
      if (el.name == "到货明细") {
        obj.slotName = "viewList";
      } else {
        obj.prop = el.prop;
      }
      list.push(obj);
    });
    this.tableThead = list;

    this.search();
    this.getMaterialList();
    this.getSupplierList();
    this.getstordocList();
    this.getUnitList();
    this.getOederList();
    this.getPersonList();
  },
  methods: {
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == "inStorage") {
        this.goTo(rowData);
      } else if (item.flag == "delete") {
        this.handleDelete([rowData]);
      } else if (item.flag == "check") {
        this.check(rowData);
      } else if (item.flag == "detail") {
        this.check(rowData);
      }
      this.addEditFlag = item.flag;
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = [];
      list.forEach((item, index) => {
        if (item.param == "supplierNo") {
          let selectOptions = this.SupplierList.map((data) => {
            return {
              text: data.supplierName,
              value: data.supplierNo,
            };
          });
          item.selectOptions = selectOptions;
        }
        if (item.param == "personNo") {
          let selectOptions = this.personList.map((data) => {
            return {
              text: data.person.name,
              value: data.personNo,
            };
          });
          item.selectOptions = selectOptions;
        }
      });
      this.$nextTick(() => {
        this.$set(this, "formItemList", list);
      });
      console.log(this.formItemList);
    },
    // 多选方法
    selectionChange(val) {
      this.selectionList = val || [];
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentPage = val;
      this.getTableDataList();
    },
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.add();
      } else if (flag == "delete") {
        if (this.selectionList.length > 0) {
          this.handleDelete(this.selectionList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      }
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 跳转入库
    goTo(row) {
      this.$router.push({
        name: "put-in-storage",
        params: { arriveOrderNo: row.arriveOrderNo, isTo: "toAdd" },
      });
    },
    // 获取所有物料
    getMaterialList() {
      materialApi.getqueryList({}).then((res) => {
        if (res.code === 1) {
          this.materialList = res.data;
        }
      });
    },
    // 获取人员列表
    getPersonList() {
      personApi.getStaffListByCondition().then((res) => {
        if (res.code === 1) {
          this.personList = res.data;
          let list = [];
          this.setFormOptions();
          res.data.forEach((item) => {
            list.push({
              name: item.person.name,
              value: item.personNo,
            });
          });
          this.setOptions(this.formConfig, "personNo", list);
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "receiverName") {
              this.$set(this.formDatalists[index].typeObj, "list", list);
            }
          });
        }
      });
    },
    // 获取所有订单
    getOederList() {
      orderApi
        .conditionQuery({ completeStatus: false, forderStatus: 1 })
        .then((res) => {
          if (res.code === 1) {
            let list = [];
            res.data.forEach((item) => {
              list.push({
                name: item.orderNo,
                value: item.orderNo,
              });
            });
            this.setOptions(this.formConfig, "orderNo", list);
            this.formDatalists.forEach((item, index) => {
              if (item.prop === "orderNo") {
                this.$set(this.formDatalists[index].typeObj, "list", list);
              }
            });
            this.formDatalists.forEach((item, index) => {
              if (item.prop === "personName") {
                this.$set(this.formDatalists[index].typeObj, "list", list);
              }
            });
          }
        });
    },
    getCount(event, index) {
      let a = this.formData.arriveOrderDetailList[index].produceDate; // 生产日期
      let b = this.formData.arriveOrderDetailList[index].lifeDays; // 保质期
      let c = this.formData.arriveOrderDetailList[index].expirationDate; // 失效日期
      if (a && b) {
        let time = new Date(a.replace(/-/, "/"));
        let newDate = new Date(time.getTime() + b * (1000 * 60 * 60 * 24));
        console.log(newDate);
        let year = newDate.getFullYear();
        let mon = newDate.getMonth() + 1;
        let day = newDate.getDate();
        console.log(year, mon, day);
        let date = year + "-" + mon + "-" + day;
        this.$set(
          this.formData.arriveOrderDetailList[index],
          "expirationDate",
          date
        );
      }
      if (a && c) {
        let a1 = Date.parse(new Date(a));
        let a2 = Date.parse(new Date(c));
        let day = parseInt((a2 - a1) / (1000 * 60 * 60 * 24));
        this.$set(this.formData.arriveOrderDetailList[index], "lifeDays", day);
      }
    },
    // 获取仓库X
    getstordocList() {
      warehouseApi.conditionQuery({}).then((res) => {
        if (res.code === 1) {
          this.stordocList = res.data;
        }
      });
    },
    // 获取单位列表X
    getUnitList() {
      unitApi.getallunitlist({}).then((res) => {
        if (res.code === 1) this.unitList = res.data;
        console.log(this.unitList, ' this.unitList');
      });
    },
    // 获取供应商
    getSupplierList() {
      supplierApi.conditionQuery({}).then((res) => {
        if (res.code === 1) {
          let list = [];
          this.SupplierList = res.data;
          this.setFormOptions();
          // 提供表头搜索数据
          res.data.forEach((item) => {
            list.push({
              name: item.supplierName,
              value: item.supplierNo,
            });
          });
          this.setOptions(this.formConfig, "supplierNo", list);
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "supplierName") {
              this.$set(this.formDatalists[index].typeObj, "list", list);
            }
          });
        }
      });
    },
    timeEvent(event, prop) {
      if (prop === "arriveTime") {
        this.formData.arriveOrderDetailList.forEach((item, index) => {
          this.$set(
            this.formData.arriveOrderDetailList[index],
            "arriveTime",
            event
          );
        });
      }
    },
    // 获取单个商品
    getGoods(event, index) {
      materialApi.getqueryList({ materialNo: event }).then((res) => {
        this.formData.arriveOrderDetailList[index].unitNo = res.data[0].unitNo;
        this.formData.arriveOrderDetailList[index].castUnitNo =
          res.data[0].unitNo;
      });
    },
    // 获取单个供应商
    getSelectData(event, prop) {
      // 获取单个订单
      if (prop === "orderNo" && event) {
        orderApi.numberQuery(event).then((res) => {
          if (res.code === 1) {
            this.$set(this.formData, "supplierNo", res.data.supplierNo);
            this.$set(this.formData, "buyerName", res.data.buyerName);
            this.$set(this.formData, "totalQuantity", res.data.totalQuantity);
            this.$set(this.formData, "totalPrice", res.data.totalPrice);
            this.formData.supplierName = res.data.supplierName;
            this.getOrderDetailList(event);
            this.$refs.formData.validate();
          }
        });
      } else if (prop === "receiverName") {
        this.personList.forEach((item) => {
          if (event === item.personNo) {
            this.formData.receiverName = item.person.name;
          }
        });
      } else {
        return;
      }
    },
    // 选择到货商品
    chooseGoods(e) {
      let price = 0;
      this.$set(this.formData, "arriveOrderDetailList", e);
      this.formData.arriveOrderDetailList.forEach((item, index) => {
        this.$set(
          this.formData.arriveOrderDetailList[index],
          "shouldArriveNum",
          item.confirmQuantity
        );
        this.$set(
          this.formData.arriveOrderDetailList[index],
          "arriveTime",
          this.formData.arriveTime
        );
        price += item.totalPrice;
      });
      this.$set(this.formData, "totalPrice", price);
    },
    // 获取订单详细列表
    getOrderDetailList(e) {
      orderDetailApi.numberQuery(e).then((res) => {
        if (res.code === 1) {
          this.$set(this.formData, "arrivalGoodsList", []);
          this.arrivalGoodsList = res.data;
          this.$set(this.formData, "arrivalGoodsList", [
            this.arrivalGoodsList[0],
          ]);
          this.chooseGoods([this.arrivalGoodsList[0]]);
        }
      });
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        organizationNo: sessionStorage.organizationNo,
        breedTypeNo: sessionStorage.breedTypeNo,
        entity: { ...this.searchlist },
      };
      arrivalGoodsApi.pageQuery(params).then((res) => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.dataList = data.content || [];
          this.total = data.totalElements;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map((item) => item.arriveOrderNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },

    handleDelete(list) {
      let selectedStaffList = [];
      list.forEach((item) => {
        selectedStaffList.push(item.supplierNo);
      });
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          let params = {
            noList: selectedStaffList,
          };
          arrivalGoodsApi.numberDel(params).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => { });
    },
    add() {
      this.formData = {};
      this.arrivalGoodsList = [];
      this.nowChanceStau = "add";
      this.titleText = "添加到货通知";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = { ...row };
      orderDetailApi.numberQuery(row.arriveOrderNo).then((res) => {
        this.$set(this.formData, "arriveOrderDetailList", res.data);
      });
      this.nowChanceStau = "edit";
      this.titleText = "修改到货通知";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    lookInfo(e) {
      this.formData = {};
      arrivalDetailAoi.queryListByOrderNo(e).then((res) => {
        if (res.code === 1) {
          this.$set(this.formData, "arriveOrderDetailList", res.data);
        }
      });
      this.nowChanceStau = "lookInfo";
      this.titleText = "查看到货明细";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    addDetail(e, index) {
      let validateFieldList = [];
      this.$refs["formData"].validateField(
        [
          "arriveOrderDetailList." + index + ".materialNo",
          "arriveOrderDetailList." + index + ".confirmQuantity",
          "arriveOrderDetailList." + index + ".castUnitNo",
          "arriveOrderDetailList." + index + ".unitNo",
          "arriveOrderDetailList." + index + ".exchangeRate",
          "arriveOrderDetailList." + index + ".primaryQuantity",
          "arriveOrderDetailList." + index + ".price",
          "arriveOrderDetailList." + index + ".packNum",
          "arriveOrderDetailList." + index + ".totalPrice",
          "arriveOrderDetailList." + index + ".address",
        ],
        (valid) => {
          if (!valid) {
            validateFieldList.push(valid);

            // 因为我这里总共校验了三个字段,所有最终三个字段都校验成功之后,数组中会有三个""
            if (
              validateFieldList.length === 10 &&
              validateFieldList.every((item) => item === "")
            ) {
              orderDetailApi.add(e).then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  orderDetailApi.numberQuery(e.orderNo).then((res) => {
                    this.$set(this.formData, "orderDetailList", res.data);
                  });
                } else {
                  this.$message.warning(res.msg || "添加失败");
                }
              });
            }
            // 校验不通过走这里
            return;
          } else {
            return false;
          }
        }
      );
    },
    editDetail(e) {
      this.$confirm("确定修改该条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          orderDetailApi.edit(e).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
            } else {
              this.$message.warning(res.msg || "修改失败");
            }
          });
        })
        .catch(() => { });
    },
    delDetial(e, index) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          orderDetailApi.numberQuery(e.orderNo).then((res) => {
            if (res.data.length <= 1) {
              this.$message.warning("已是最后一条数据禁止删除");
            } else {
              orderDetailApi.numberDel(e.orderDetailNo).then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.formData.orderDetailList.splice(index, 1);
                } else {
                  this.$message.warning(res.msg || "删除失败");
                }
              });
            }
          });
        })
        .catch(() => { });
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          // 添加仓库名称
          this.formData.arriveOrderDetailList.forEach((item, index) => {
            if (item.stordocNo) {
              this.stordocList.forEach((item1) => {
                if (item1.stordocNo === item.stordocNo) {
                  this.formData.arriveOrderDetailList[index].stordocName =
                    item1.stordocName;
                }
              });
            }
          });
          if (this.nowChanceStau === "edit") {
            arrivalGoodsApi.edit(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            arrivalGoodsApi.add(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep .el-dialog__wrapper .el-dialog .el-form-item .el-form-item__label {
  min-width: 140px;
}

::v-deep .el-form-item[data-v-3d395f82] {
  display: flex;
  margin-bottom: 10px;
  margin-right: 20px;
}

::v-deep .el-dialog__body {
  max-height: 66vh;
  overflow-y: auto;
}

::v-deep .el-form {
  display: flex;
  flex-wrap: wrap;

  .el-form-item__content {
    display: flex;
    margin-right: 20px;
  }
}

.xunhuan {
  margin-bottom: 50px;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .goods {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: left;
    padding-left: 140px;
  }

  .editBox {
    z-index: 100;
    position: absolute;
    right: 0px;
    bottom: -30px;
  }
}

.zhu {
  display: flex;

  ::v-deep .el-input__inner {
    background-color: rgb(241, 239, 239) !important;
  }
}

.numberUnit {
  display: flex;

  .one {
    width: 75%;
  }

  .two {
    width: 25%;
  }
}
</style>
